<script setup lang="ts">

export interface Message {
  id: number;
  name: string;
  email: string;
  phone: string;
  content: string;
  created_at: string;
}

defineProps<{
  messages: Message[];
  loading: boolean;
  error: string;
  currentPage: number;
  pageSize: number;
  totalMessages: number;
}>();

const emit = defineEmits<{
  (e: 'delete', id: number): void;
  (e: 'page-change', page: number): void;
}>();

const handleDelete = (id: number) => {
  emit('delete', id);
};

const handlePageChange = (page: number) => {
  emit('page-change', page);
};
</script>

<template>
  <div class="message-management">
    <h2>留言管理</h2>
    <div v-if="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <div class="pagination">
        <button 
          @click="handlePageChange(currentPage - 1)" 
          :disabled="currentPage <= 1"
        >
          上一页
        </button>
        <span>第 {{ currentPage }} 页</span>
        <button 
          @click="handlePageChange(currentPage + 1)" 
          :disabled="currentPage * pageSize >= totalMessages"
        >
          下一页
        </button>
      </div>
      
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>内容</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="message in messages" :key="message.id">
            <td>{{ message.id }}</td>
            <td>{{ message.name }}</td>
            <td>{{ message.email }}</td>
            <td>{{ message.phone }}</td>
            <td>{{ message.content }}</td>
            <td>{{ new Date(message.created_at).toLocaleString() }}</td>
            <td>
              <button 
                @click="handleDelete(message.id)" 
                class="btn-delete"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped>
.message-management {
  margin: 20px 0;
}

.pagination {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination button {
  padding: 5px 10px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
}

.pagination button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

th, td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f5f5f5;
}

.btn-delete {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

.error {
  color: #f44336;
  margin-bottom: 15px;
}
</style>